package com.example.controller;

import com.example.config.MQConfiguration;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
public class ProducerController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private MQConfiguration mqConfiguration;

    @GetMapping("/send")
    public String sendMessage() {
        String message = "Message at " + System.currentTimeMillis();
        String topic = mqConfiguration.getTopic();
        String tag = mqConfiguration.getTargetTag();
        String destination = topic + ":" + tag;

        rocketMQTemplate.convertAndSend(destination, message);
        return "Sent to " + destination + ": " + message;
    }

    @GetMapping("/getAllProviders")
    public void getAllProviders() {
        Collection<ProviderModel> providerModels = ApplicationModel.defaultModel().getApplicationServiceRepository().allProviderModels();

        for (ProviderModel providerModel : providerModels) {
            // 获取关联的ServiceConfig
            Object config = providerModel.getServiceConfig();
            if (config instanceof ServiceConfig ) {
                ServiceConfig<?> serviceConfig = (ServiceConfig<?>) config;
                System.out.println(serviceConfig.getInterface());
            }
        }
    }

    @GetMapping("/unexportProviders")
    public void unexportProviders() {
        Collection<ProviderModel> providerModels = ApplicationModel.defaultModel().getApplicationServiceRepository().allProviderModels();

        for (ProviderModel providerModel : providerModels) {
            // 获取关联的ServiceConfig
            Object config = providerModel.getServiceConfig();
            if (config instanceof ServiceConfig ) {
                ServiceConfig<?> serviceConfig = (ServiceConfig<?>) config;
                if (!"org.apache.dubbo.metadata.MetadataService".equals(serviceConfig.getInterface())) {
                    serviceConfig.unexport();
                    System.out.println(serviceConfig.getInterface() + " unexported");
                }
            }
        }
    }
}